<template>
  <div class="notification-statistics">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日发送量</span>
              <el-tag size="small" :type="todayTrend > 0 ? 'success' : 'danger'">
                {{ todayTrend > 0 ? '+' : '' }}{{ todayTrend }}%
              </el-tag>
            </div>
          </template>
          <div class="card-value">
            <span class="number">{{ statistics.todayCount }}</span>
            <span class="unit">条</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月发送量</span>
              <el-tag size="small" :type="monthTrend > 0 ? 'success' : 'danger'">
                {{ monthTrend > 0 ? '+' : '' }}{{ monthTrend }}%
              </el-tag>
            </div>
          </template>
          <div class="card-value">
            <span class="number">{{ statistics.monthCount }}</span>
            <span class="unit">条</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均发送成功率</span>
            </div>
          </template>
          <div class="card-value">
            <span class="number">{{ statistics.successRate }}</span>
            <span class="unit">%</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均响应时间</span>
            </div>
          </template>
          <div class="card-value">
            <span class="number">{{ statistics.avgResponseTime }}</span>
            <span class="unit">分钟</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势分析图表 -->
    <el-row :gutter="20" class="statistics-charts">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>发送量趋势</span>
              <div class="chart-actions">
                <el-radio-group v-model="trendTimeRange" size="small">
                  <el-radio-button label="day">日</el-radio-button>
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                </el-radio-group>
                <el-date-picker
                  v-model="trendDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                  :shortcuts="dateShortcuts"
                  @change="handleTrendDateChange"
                />
              </div>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>渠道分布</span>
            </div>
          </template>
          <div ref="channelChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="statistics-charts">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>消息类型分布</span>
            </div>
          </template>
          <div ref="typeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>发送成功率趋势</span>
            </div>
          </template>
          <div ref="successRateChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 渠道分析表格 -->
    <el-card class="channel-table">
      <template #header>
        <div class="table-header">
          <span>渠道分析</span>
          <div class="table-actions">
            <el-button type="primary" @click="exportChannelData">
              导出数据
            </el-button>
          </div>
        </div>
      </template>
      <el-table
        :data="channelData"
        border
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="channel" label="渠道" width="120" />
        <el-table-column prop="todayCount" label="今日发送量" width="120" sortable />
        <el-table-column prop="monthCount" label="本月发送量" width="120" sortable />
        <el-table-column prop="successRate" label="成功率" width="120" sortable>
          <template #default="{ row }">
            {{ row.successRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="avgResponseTime" label="平均响应时间" width="150" sortable>
          <template #default="{ row }">
            {{ row.avgResponseTime }}分钟
          </template>
        </el-table-column>
        <el-table-column prop="errorRate" label="错误率" width="120" sortable>
          <template #default="{ row }">
            <el-tag :type="row.errorRate > 5 ? 'danger' : 'warning'">
              {{ row.errorRate }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'normal' ? 'success' : 'danger'">
              {{ row.status === 'normal' ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewChannelDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 渠道详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`${currentChannel?.channel}详情`"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="渠道名称">
          {{ currentChannel?.channel }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentChannel?.status === 'normal' ? 'success' : 'danger'">
            {{ currentChannel?.status === 'normal' ? '正常' : '异常' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="今日发送量">
          {{ currentChannel?.todayCount }}条
        </el-descriptions-item>
        <el-descriptions-item label="本月发送量">
          {{ currentChannel?.monthCount }}条
        </el-descriptions-item>
        <el-descriptions-item label="成功率">
          {{ currentChannel?.successRate }}%
        </el-descriptions-item>
        <el-descriptions-item label="错误率">
          {{ currentChannel?.errorRate }}%
        </el-descriptions-item>
        <el-descriptions-item label="平均响应时间">
          {{ currentChannel?.avgResponseTime }}分钟
        </el-descriptions-item>
        <el-descriptions-item label="最后更新时间">
          {{ currentChannel?.updateTime }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="detail-charts">
        <div ref="channelTrendChartRef" class="detail-chart"></div>
        <div ref="channelErrorChartRef" class="detail-chart"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  getNotificationStatistics,
  getNotificationTrend,
  getChannelDistribution,
  getTypeDistribution,
  getSuccessRateTrend,
  getChannelAnalysis,
  exportChannelAnalysis
} from '@/api/message'

// 统计数据
const statistics = reactive({
  todayCount: 0,
  monthCount: 0,
  successRate: 0,
  avgResponseTime: 0
})

// 趋势数据
const trendTimeRange = ref('day')
const trendDateRange = ref([])
const trendChartRef = ref(null)
const channelChartRef = ref(null)
const typeChartRef = ref(null)
const successRateChartRef = ref(null)
const channelTrendChartRef = ref(null)
const channelErrorChartRef = ref(null)

// 图表实例
let trendChart = null
let channelChart = null
let typeChart = null
let successRateChart = null
let channelTrendChart = null
let channelErrorChart = null

// 表格数据
const channelData = ref([])
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const currentChannel = ref(null)

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 计算趋势
const todayTrend = ref(0)
const monthTrend = ref(0)

// 初始化
onMounted(async () => {
  await initData()
  initCharts()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  disposeCharts()
})

// 初始化数据
const initData = async () => {
  try {
    const [statsRes, channelRes] = await Promise.all([
      getNotificationStatistics(),
      getChannelAnalysis({
        page: currentPage.value,
        pageSize: pageSize.value
      })
    ])

    Object.assign(statistics, statsRes.data)
    channelData.value = channelRes.data.list
    total.value = channelRes.data.total

    // 计算趋势
    todayTrend.value = statsRes.data.todayTrend
    monthTrend.value = statsRes.data.monthTrend
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 初始化图表
const initCharts = () => {
  trendChart = echarts.init(trendChartRef.value)
  channelChart = echarts.init(channelChartRef.value)
  typeChart = echarts.init(typeChartRef.value)
  successRateChart = echarts.init(successRateChartRef.value)

  loadTrendData()
  loadChannelDistribution()
  loadTypeDistribution()
  loadSuccessRateTrend()
}

// 加载趋势数据
const loadTrendData = async () => {
  try {
    const res = await getNotificationTrend({
      timeRange: trendTimeRange.value,
      startDate: trendDateRange.value[0],
      endDate: trendDateRange.value[1]
    })

    trendChart.setOption({
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['发送量', '成功量']
      },
      xAxis: {
        type: 'category',
        data: res.data.dates
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '发送量',
          type: 'line',
          data: res.data.counts
        },
        {
          name: '成功量',
          type: 'line',
          data: res.data.successCounts
        }
      ]
    })
  } catch (error) {
    console.error('获取趋势数据失败:', error)
    ElMessage.error('获取趋势数据失败')
  }
}

// 加载渠道分布数据
const loadChannelDistribution = async () => {
  try {
    const res = await getChannelDistribution()

    channelChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: res.data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  } catch (error) {
    console.error('获取渠道分布数据失败:', error)
    ElMessage.error('获取渠道分布数据失败')
  }
}

// 加载类型分布数据
const loadTypeDistribution = async () => {
  try {
    const res = await getTypeDistribution()

    typeChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '20',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: res.data
        }
      ]
    })
  } catch (error) {
    console.error('获取类型分布数据失败:', error)
    ElMessage.error('获取类型分布数据失败')
  }
}

// 加载成功率趋势数据
const loadSuccessRateTrend = async () => {
  try {
    const res = await getSuccessRateTrend()

    successRateChart.setOption({
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: res.data.dates
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [
        {
          type: 'line',
          data: res.data.rates,
          markLine: {
            data: [{ type: 'average', name: '平均值' }]
          }
        }
      ]
    })
  } catch (error) {
    console.error('获取成功率趋势数据失败:', error)
    ElMessage.error('获取成功率趋势数据失败')
  }
}

// 处理窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  channelChart?.resize()
  typeChart?.resize()
  successRateChart?.resize()
  channelTrendChart?.resize()
  channelErrorChart?.resize()
}

// 销毁图表实例
const disposeCharts = () => {
  trendChart?.dispose()
  channelChart?.dispose()
  typeChart?.dispose()
  successRateChart?.dispose()
  channelTrendChart?.dispose()
  channelErrorChart?.dispose()
}

// 处理趋势时间范围变化
const handleTrendDateChange = () => {
  loadTrendData()
}

// 处理表格分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadChannelData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadChannelData()
}

// 加载渠道数据
const loadChannelData = async () => {
  tableLoading.value = true
  try {
    const res = await getChannelAnalysis({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    channelData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取渠道数据失败:', error)
    ElMessage.error('获取渠道数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 查看渠道详情
const viewChannelDetail = async (channel) => {
  currentChannel.value = channel
  detailDialogVisible.value = true

  // 初始化详情图表
  await nextTick()
  channelTrendChart = echarts.init(channelTrendChartRef.value)
  channelErrorChart = echarts.init(channelErrorChartRef.value)

  // 加载详情数据
  try {
    const [trendRes, errorRes] = await Promise.all([
      getNotificationTrend({
        channel: channel.code,
        timeRange: 'week'
      }),
      getChannelErrorAnalysis(channel.code)
    ])

    // 设置趋势图表
    channelTrendChart.setOption({
      title: {
        text: '发送趋势'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: trendRes.data.dates
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          type: 'line',
          data: trendRes.data.counts
        }
      ]
    })

    // 设置错误分析图表
    channelErrorChart.setOption({
      title: {
        text: '错误分析'
      },
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: errorRes.data
        }
      ]
    })
  } catch (error) {
    console.error('获取渠道详情数据失败:', error)
    ElMessage.error('获取渠道详情数据失败')
  }
}

// 导出渠道数据
const exportChannelData = async () => {
  try {
    const res = await exportChannelAnalysis()
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `渠道分析数据_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  }
}
</script>

<style lang="scss" scoped>
.notification-statistics {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-value {
      text-align: center;
      padding: 10px 0;

      .number {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
      }

      .unit {
        font-size: 14px;
        color: #909399;
        margin-left: 4px;
      }
    }
  }

  .statistics-charts {
    margin-bottom: 20px;

    .chart-card {
      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .chart-actions {
          display: flex;
          gap: 16px;
        }
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .channel-table {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .detail-charts {
    margin-top: 20px;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;

    .detail-chart {
      height: 300px;
    }
  }
}
</style> 